<template>
  <el-card>
    <!-- 页面 -->
    <div>
      <div class="search">
        物料编号:
        <el-input
          v-model="in_materialNumber"
          placeholder="请输入物料编号"
          size="small"
          clearable
        ></el-input>
        物料名称:
        <el-input
          v-model="in_materialName"
          placeholder="请输入物料名称"
          size="small"
          clearable
        ></el-input>
        供应商名:
        <el-input
          v-model="in_pname"
          placeholder="请输入供应商名"
          size="small"
          clearable
        ></el-input>
        <el-button
          class="detail"
          icon="el-icon-search"
          @click="checkMaterial"
          size="small"
          >查询</el-button
        >
        <el-button class="rePassword" icon="el-icon-refresh-right" size="small"
          >重置</el-button
        >
        <el-button
          class="addUser"
          icon="el-icon-plus"
          @click="dialogFormVisible = true"
          size="small"
          >新增物料</el-button
        >

        <!-- <el-upload
          class="upload-demo"
          action="http://localhost:8080/easyExcel/input"
          :on-success="uploadSuccess"
          :on-remove="beforeRemove"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-button
            icon="el-icon-s-fold"
            size="small"
            class="itmaterial addUser"
            >物料导入</el-button
          >
        </el-upload> -->
      </div>

      <div class="box">
        <el-table
          ref="multipleTable"
          :data="data"
          tooltip-effect="dark"
          style="width: 100%"
          :row-style="{ height: '60px', padding: '0 0' }"
          @selection-change="handleSelectionChange"
          border
          stripe
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="materialNumber" label="物料编号" width="204">
            <!-- <template slot-scope="scope">{{ scope.row.date }}</template> -->
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称" width="500">
          </el-table-column>
          <el-table-column
            prop="materialShort"
            label="物料简称"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column prop="unit" label="单位" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button class="addUser" size="mini" @click="bianji(scope)"
                >编辑</el-button
              >
              <el-button
                @click="handleDelete(scope.$index, scope.row)"
                class="rePassword"
                size="mini"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->

        <el-pagination
          @size-change="sizeChange"
          @current-change="pageChange"
          :current-page="page"
          :page-sizes="[3, 5, 10, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <!-- 物料添加弹出框 -->
      <el-dialog
        title="添加物料"
        :visible.sync="dialogFormVisible"
        width="600px"
        show-close
      >
        <el-form :model="addData">
          <el-form-item label="物料编号" :label-width="formLabelWidth">
            <el-input
              v-model="addData.materialNumber"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="物料名称" :label-width="formLabelWidth">
            <el-input
              v-model="addData.materialName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="物料简称" :label-width="formLabelWidth">
            <el-input
              v-model="addData.materialShort"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="单位" :label-width="formLabelWidth">
            <el-input v-model="addData.unit" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addmaterial">确 定</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 物料编辑弹出框 -->
      <el-dialog title="编辑物料" :visible.sync="editForm" width="600px">
        <el-form :model="addData">
          <el-form-item label="物料编号" :label-width="formLabelWidth">
            <el-input
              v-model="editData.materialNumber"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="物料名称" :label-width="formLabelWidth">
            <el-input
              v-model="editData.materialName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="物料简称" :label-width="formLabelWidth">
            <el-input
              v-model="editData.materialShort"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="单位" :label-width="formLabelWidth">
            <el-input v-model="editData.unit" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="edit">确 定</el-button>
          <el-button @click="editForm = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      in_materialNumber: '',
      in_materialName: '',
      in_pname: '',
      data: [],
      total: 0,
      pageSize: 10,
      page: 1,
      dialogFormVisible: false,
      editForm: false,
      formLabelWidth: '200px',
      addData: {
        materialNumber: '',
        materialName: '',
        materialShort: '',
        unit: ''
      },
      editData: {
        // materialId:'',
        materialNumber: '',
        materialName: '',
        materialShort: '',
        unit: ''
      },
      // 文件上传表
      fileList: []
    };
  },
  methods: {
    show() {
      // console.log(this.tableData);
    },

    // 获取当前页数
    pageChange(e) {
      console.log(123);
      this.page = e;

      // 查询时获取当前页数
      if (this.in_materialName != '' || this.in_materialNumber != '') {
        this.axios({
          url: `/material/materialList/${this.page}/${this.pageSize}`,
          method: 'get',
          params: {
            materialName: this.in_materialName,
            materialNumber: this.in_materialNumber
          }
        }).then(res => {
          if (res.data.code == 200) {
            // console.log(res);
            // console.log(res);
            this.data = res.data.data.list;
            this.total = res.data.data.total;
            // this.$message({
            //       type: "success",
            //       message: "查询成功",
            //   });
          }
        });
      } else {
        this.axios({
          url: `/material/materialList/${this.page}/${this.pageSize}`
        }).then(res => {
          // console.log(res);
          this.data = res.data.data.list;
          this.total = res.data.data.total;
        });
      }
    },

    // 改变页面容量
    sizeChange(e) {
      this.pageSize = e;
      if (this.in_materialName != '' || this.in_materialNumber != '') {
        // 查询时改变页面容量
        this.axios({
          url: `/material/materialList/${this.page}/${this.pageSize}`,
          method: 'get',
          params: {
            materialName: this.in_materialName,
            materialNumber: this.in_materialNumber
          }
        }).then(res => {
          if (res.data.code == 200) {
            // console.log(res);
            this.data = res.data.data.list;
            this.total = res.data.data.total;
            this.$message({
              type: 'success',
              message: '查询成功'
            });
          }
        });
      } else {
        this.axios({
          url: `/material/materialList/${this.page}/${this.pageSize}`
        }).then(res => {
          // console.log(res);
          this.data = res.data.data.list;
          this.total = res.data.data.total;
        });
      }
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 查询物料
    checkMaterial() {
      this.axios({
        url: `/material/materialList/${this.page}/${this.pageSize}`,
        method: 'get',
        params: {
          materialName: this.in_materialName,
          materialNumber: this.in_materialNumber
        }
      }).then(res => {
        if (res.data.code == 200) {
          // console.log(res);
          if (this.in_materialNumber != '' || this.in_materialName != '') {
            if (res.data.data.list.length == 0) {
              this.$message({
                type: 'error',
                message: '查询失败，请确保物料编号(名称)输入正确'
              });
            } else {
              this.data = res.data.data.list;
              this.total = res.data.data.total;
              this.$message({
                type: 'success',
                message: '查询成功'
              });
            }
          } else {
            this.$message({
              type: 'error',
              message: '查询失败，请确保物料编号(名称)输入正确'
            });
          }
        }
      });
    },

    // 编辑前先把数据渲染上去
    bianji(scope) {
      this.editForm = true;
      this.axios({
        url: `/material/getMaterialById/${scope.row.materialId}`,
        method: 'get'
      }).then(res => {
        if (res.data.code == 200) {
          console.log(res);
          this.editData = res.data.data.materialInfo;
        }
      });
    },

    // 编辑物料
    edit() {
      (this.editForm = false),
        this.axios({
          url: `/material/updateMaterial`,
          method: 'post',
          data: this.editData
        }).then(res => {
          if (res.data.code == 200) {
            var nowpage = this.page;
            this.pageChange(nowpage);
            // location.reload( )
            this.$message({
              type: 'success',
              message: '编辑成功'
            });
          }
        });
    },

    // 添加物料
    addmaterial() {
      (this.dialogFormVisible = false),
        this.axios({
          url: '/material/saveMaterial',
          method: 'post',
          data: this.addData
        }).then(res => {
          console.log(res.config.data);
          if (res.data.code == 200) {
            var changepage = Math.ceil((this.total + 1) / this.pageSize);
            this.pageChange(changepage),
              // location.reload()
              this.$message({
                type: 'success',
                message: '物料添加成功!'
              });
          }
        });
    },

    //删除物料
    handleDelete(index, row) {
      // console.log(index, row);
      this.$confirm('确认删除该物料吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.axios({
            url: `/material/deleteMaterial/${row.materialId}`,
            method: 'DELETE'
          }).then(res => {
            // console.log(res);
            if (res.data.code == 200) {
              // 为了提升用户体验感，先对数据库中的数据进行操作，再删除dom结点
              this.data = this.data.filter((v, i) => {
                // console.log(v,i);
                return v.materialId != row.materialId;
              });

              // 删除后改变数组长度使分页正确
              this.total = this.total - 1;

              // 在删除每一条数据时都要判断是否最后一条数据
              // 如果当前为第一页且无其他页面时且删除最后一条数据---提示无数据
              // 如果当前为第一页且有其它页面时且删除到最后一条数据---reloa d
              // 如果当前不是第一页，且删除到最后一条数据时，就调用pageChange方法
              // 如果total  pageSize
              // 4 5  0 1
              // 5 5  1 1
              // 6 5  1 2
              // 10 5  2 2
              if (this.data.length == 0) {
                if (
                  this.page == 1 &&
                  (this.total / this.pageSize == 1 ||
                    this.total / this.pageSize == 0)
                ) {
                  this.$message({
                    type: 'success',
                    message: '无数据!'
                  });
                } else if (
                  this.page == 1 &&
                  ((this.total / this.pageSize == 1 &&
                    this.total % this.pageSize != 0) ||
                    this.total / this.pageSize > 1)
                ) {
                  location.reload();
                } else if (this.page != 1) {
                  this.pageChange(this.page - 1);
                }
              }
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          });
        })
        .catch(() => {
          console.log(row);
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    // 物料上传

    handlePreview(file) {
      // console.log(file);
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    uploadSuccess(response, file, fileList) {
      this.pageChange(1);
    }
  },

  // 挂载渲染
  mounted() {
    this.axios({
      url: `/material/materialList/${this.page}/${this.pageSize}`
    }).then(res => {
      // console.log(res);
      this.data = res.data.data.list;
      this.total = res.data.data.total;
    });
  }
};
</script>

<style scoped>
.el-input {
  width: 200px;
  margin-right: 10px;
}
.search {
  border-top: 2px solid #9999;
  padding-top: 30px;
  margin-top: 15px;
}
.box {
  padding-top: 30px;
}
.el-pagination {
  margin-top: 25px;
  float: right;
}
.el-table .cell {
  text-align: center;
}
.el-table /deep/ td .cell,
.el-table /deep/ th .cell {
  text-align: center;
}
.itmaterial {
  margin-top: 10px;
}
.upload-demo {
  width: 150px;
  display: inline-block;
  margin-left: 10px;
}
</style>
